/**
 * setup http request config
 */
import axios from 'axios'
import { message } from 'antd'
import store from '@/store'

axios.defaults.timeout = 30000
axios.defaults.baseURL = '/api'

/**
 * http request interceptor
 */
axios.interceptors.request.use(
  (config) => {
    console.log('🚀 ~ config', config)
    if (config?.data) {
      if (config?.type === 'json') {
        config.headers = {
          'Content-Type': 'application/json' // json
        }
        config.data = JSON.stringify(config.data)
      } else {
        const form = new FormData()
        Object.keys(config.data).forEach((key) => {
          form.append(key, config.data[key])
        })
        config.data = form
        config.headers = {
          'Content-Type': 'application/x-www-form-urlencoded' // formData
        }
      }
    }
    config.headers = {
      ...config.headers,
      Authorization: store.getState().user.token || ''
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

/**
 * http response interceptor
 */
axios.interceptors.response.use(
  (response) => {
    console.log(response?.config.url, response)
    if (response?.status !== 200) message.error('network error')
    else if (response?.data?.code !== 200)
      message.error(response?.data?.message)
    return response.data
  },
  (error) => {
    message.error(error.toString())
  }
)

/**
 * get method
 * @param url  request url
 * @param params  request params
 * @returns {Promise}
 */
export function get(url, params = {}, config = {}) {
  return new Promise((resolve, reject) => {
    axios
      .get(url, {
        params: params,
        ...config
      })
      .then((response) => {
        resolve(response)
      })
      .catch((error) => {
        reject(error)
      })
  })
}

/**
 * post method
 * @param url
 * @param data
 * @returns {Promise}
 */

export function post(url, data, config = {}) {
  return new Promise((resolve, reject) => {
    axios.post(url, data, config).then(
      (response) => {
        resolve(response)
      },
      (err) => {
        reject(err)
      }
    )
  })
}

/**
 * patch request
 * @param url
 * @param data
 * @returns {Promise}
 */
export function patch(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.patch(url, data).then(
      (response) => {
        resolve(response)
      },
      (err) => {
        message.error(err.toString())
        reject(err)
      }
    )
  })
}

/**
 * put request
 * @param url
 * @param data
 * @returns {Promise}
 */

export function put(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.put(url, data).then(
      (response) => {
        resolve(response)
      },
      (err) => {
        message.error(err.toString())
        reject(err)
      }
    )
  })
}

/**
 * delete request
 * @param url
 * @param params
 * @returns {Promise}
 */

export function deleteFunc(url, params = {}) {
  return new Promise((resolve, reject) => {
    axios.delete(url, { params }).then(
      (response) => {
        resolve(response)
      },
      (err) => {
        message.error(err.toString())
        reject(err)
      }
    )
  })
}

// export global http request method
export default function http(type, url, param, config = {}) {
  return new Promise((resolve, reject) => {
    switch (type) {
      case 'get':
        console.log('begin a get request, and url:', url)
        get(url, param, config)
          .then(function (response) {
            resolve(response)
          })
          .catch(function (error) {
            console.log('get request GET failed.', error)
            reject(error)
          })
        break
      case 'post':
        console.log('begin a post request, and url:', url)
        post(url, param, config)
          .then(function (response) {
            resolve(response)
          })
          .catch(function (error) {
            console.log('get request POST failed.', error)
            reject(error)
          })
        break
      case 'put':
        console.log('begin a put request, and url:', url)
        put(url, param)
          .then(function (response) {
            resolve(response)
          })
          .catch(function (error) {
            console.log('get request PUT failed.', error)
            reject(error)
          })
        break
      case 'patch':
        console.log('begin a patch request, and url:', url)
        patch(url, param)
          .then(function (response) {
            resolve(response)
          })
          .catch(function (error) {
            console.log('get request PATCH failed.', error)
            reject(error)
          })
        break
      case 'delete':
        console.log('begin a delete request, and url:', url)
        deleteFunc(url, param)
          .then(function (response) {
            resolve(response)
          })
          .catch(function (error) {
            console.log('get request DELETE failed.', error)
            reject(error)
          })
        break
      default:
        break
    }
  })
}
